//
//  LongReviewDetailViewController.m
//  MovieFans
//
//  Created by 钟义 on 16/1/20.
//  Copyright © 2016年 joker. All rights reserved.
//

#import "LongReviewDetailViewController.h"
#import "AFHTTPSessionManager+Util.h"
#import "ReviewInfoModel.h"
#import "LongReviewCell.h"
#import "LongContentCell.h"
#import "LongImageViewCell.h"
#import "FXBlurView.h"
#import "DetailTableViewHeader.h"
#import "UIImageView+WebCache.h"
#import "UINavigationBar+Awesome.h"
#import "MovieDetailViewController.h"
#import "scroeToStar.h"
#import "UINavigationController+FDFullscreenPopGesture.h"

@interface LongReviewDetailViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    FXBlurView * _fxView;
}

@property (nonatomic, strong) ReviewInfoModel * longReviewModel;

@property(nonatomic,strong)UITableView* tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;

@property(nonatomic,strong)DetailTableViewHeader* headView;
@property(nonatomic,strong)UIImageView* bigImageView;

@end

@implementation LongReviewDetailViewController

- (ReviewInfoModel *)longReviewModel{
    if (!_longReviewModel) {
        _longReviewModel = [[ReviewInfoModel alloc]init];
    }
    return _longReviewModel;
}

- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

-(UITableView*)tableView
{
    if (!_tableView) {
        _tableView=[[UITableView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)style:UITableViewStylePlain];
        _tableView.delegate=self;
        _tableView.dataSource=self;
    }
    return _tableView;
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    //    self.tableView.delegate = self;
    [self scrollViewDidScroll:self.tableView];
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
    self.fd_interactivePopDisabled = YES;

    
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    //    self.tableView.delegate = nil;
    [self.navigationController.navigationBar lt_reset];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self.view addSubview:self.tableView];
    [self requestData];
    [self customNavigationItem];
    //[self requestData];
    //[self.tableView registerNib:[UINib nibWithNibName:@"LongReviewCell" bundle:nil] forCellReuseIdentifier:@"LongReviewCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"LongContentCell" bundle:nil] forCellReuseIdentifier:@"LongContentCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"LongImageViewCell" bundle:nil] forCellReuseIdentifier:@"LongImageViewCell"];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tabBarController.tabBar.hidden = YES;
    self.tableView.estimatedRowHeight = 10;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    [self.navigationController.navigationBar lt_setBackgroundColor:[UIColor clearColor]];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)customNavigationItem{
    
    UIColor * color = [UIColor whiteColor];
    NSDictionary * dict=[NSDictionary dictionaryWithObject:color forKey:NSForegroundColorAttributeName];
    self.navigationController.navigationBar.titleTextAttributes = dict;
    
    
    // 获取视图控制器的UINavigationItem
    UINavigationItem * naviItem = self.navigationItem;
    
    UIImage * leftImage = [UIImage imageNamed:@"navigationbar_icon_back"];
    UIBarButtonItem * leftBarItem = [[UIBarButtonItem alloc] initWithImage:leftImage style:UIBarButtonItemStylePlain target:self action:@selector(leftBarButtonItemClicked:)];
    leftBarItem.tintColor = [UIColor whiteColor];
    naviItem.leftBarButtonItem = leftBarItem;
    
    
    
    _bigImageView=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 200)];
    _bigImageView.clipsToBounds=YES;
    _bigImageView.contentMode = UIViewContentModeScaleAspectFill;
    _bigImageView.userInteractionEnabled = YES;
    
    
    _headView=[[DetailTableViewHeader alloc]init];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    _fxView = [[FXBlurView alloc] init];
    [_headView layoutWithTableView:self.tableView andBackGroundView:_bigImageView andSubviews:_fxView];
    
    UITapGestureRecognizer * tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(onTap:)];
    [_fxView addGestureRecognizer:tapGesture];
}

- (void)onTap:(UITapGestureRecognizer *)sender{
    
    MovieDetailViewController * MDVC = [[MovieDetailViewController alloc]init];
    MDVC.filmId = _longReviewModel.film_id;
    [self.navigationController pushViewController:MDVC animated:YES];
}


//组头自定义
- (void)createHeaderUI{
    
    [_bigImageView sd_setImageWithURL:[NSURL URLWithString:_longReviewModel.poster_url]placeholderImage:[UIImage imageNamed:@"weibo_movie_empty_offline@2x"]];
    
    //创建模糊视图
    _fxView.frame = CGRectMake(0, 130, SCREEN_WIDTH, 70);
    _fxView.dynamic = YES;
    _fxView.blurRadius = 20;
    _fxView.tintColor = [UIColor clearColor];
    
    UILabel * titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 50)];
    [_fxView addSubview:titleLabel];
    titleLabel.text = _longReviewModel.title;
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:16];;
    
    float score = [scroeToStar scroeToStarWith:_longReviewModel.score];
    int a = score * 2;
    if (a % 2 == 0) {
        for (int i = 0; i < 5;i++ ) {
            UIImageView * imageView =[[UIImageView alloc]init];
            if (i < a/2) {
                imageView.image = [UIImage imageNamed:@"rating_smallstar_selected_dark"];
            }else{
                imageView.image = [UIImage imageNamed:@"rating_smallstar_unchecked_dark"];
            }
            imageView.frame = CGRectMake(10+i*12, 50, 10, 10);
            //        imageView.center = CGPointMake(_fxView.center.x-40+i*12, _fxView.center.y-30);
            [_fxView addSubview:imageView];
        }
    }else{
        for (int i = 0; i < 5;i++ ) {
            UIImageView * imageView =[[UIImageView alloc]init];
            if (i < a/2) {
                imageView.image = [UIImage imageNamed:@"rating_smallstar_selected_dark"];
            }else if(i == a/2){
                imageView.image = [UIImage imageNamed:@"rating_smallstar_half_dark"];
            }else{
                imageView.image = [UIImage imageNamed:@"rating_smallstar_unchecked_dark"];
            }
            
            imageView.frame = CGRectMake(10+i*12, 50, 10, 10);
            [_fxView addSubview:imageView];
        }
    }
    UILabel * writerLabel = [[UILabel alloc]initWithFrame:CGRectMake(78, 50, 100, 10)];
    [_fxView addSubview:writerLabel];
    writerLabel.font = [UIFont systemFontOfSize:12];
    writerLabel.textColor = [UIColor whiteColor];
    NSDictionary * dic = (id)_longReviewModel.user;
    writerLabel.text = [NSString stringWithFormat:@"影评人:%@",[dic valueForKey:@"name"]];
    
    
    UILabel * promptLabel = [[UILabel alloc]initWithFrame:CGRectMake(SCREEN_WIDTH-100, 50, 100, 10)];
    [_fxView addSubview:promptLabel];
    promptLabel.text = @"点击查看电影详情";
    promptLabel.font = [UIFont systemFontOfSize:12];
    promptLabel.textColor = [UIColor redColor];
                        
}

- (void)leftBarButtonItemClicked:(UIBarButtonItem *)sender{
    
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    if (_tableView == scrollView) {

        UIColor * color = [UIColor blackColor];
        CGFloat offsetY = scrollView.contentOffset.y;
        if (offsetY > 20) {
            CGFloat alpha = MIN(1, 1 - ((20 + 100 - offsetY) / 100));
            [self.navigationController.navigationBar lt_setBackgroundColor:[color colorWithAlphaComponent:alpha]];
        } else {
            [self.navigationController.navigationBar lt_setBackgroundColor:[color colorWithAlphaComponent:0]];
        }
    }
}

//数据请求
- (void)requestData{
    [SVProgressHUD showWithStatus:@"加载中..." maskType:SVProgressHUDMaskTypeGradient];
    //[SVProgressHUD showWithStatus:@"加载中，请稍后..."];
    
    NSMutableDictionary *dict = @{}.mutableCopy;
    dict[@"id"] = self.ID;
    dict[@"type"] = @"long";
    dict[@"long_show"] = @"1";
    
    [AFHTTPSessionManager requestWithType:AFHTTPSessionManagerRequestTypePOST URLString:MV_LONGREVIEW_DETAIL parmaeters:dict success:^(NSURLSessionDataTask *task, id responseObject) {
        //NSLog(@"respons  = %@",responseObject);
        
        AFHTTPRequestOperationManager *manager    = [AFHTTPRequestOperationManager manager];
        // 设置超时时间
        [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
        manager.requestSerializer.timeoutInterval = 10.f;
        [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
        
        NSDictionary * longReviewDict = responseObject[@"data"][@"feed_long_show"] ;

        _longReviewModel = [[ReviewInfoModel alloc]init];
        [_longReviewModel setValuesForKeysWithDictionary:longReviewDict];
       // NSLog(@"%@",_longReviewModel.film_name);

        NSArray * arr = longReviewDict[@"html_list"];
        NSLog(@"%ld",arr.count);
        for (NSDictionary * dic in arr) {
            [self.dataArray addObject:dic];
        }
        NSLog(@"%ld",self.dataArray.count);
        
        [SVProgressHUD showSuccessWithStatus:@"加载完成"];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self.tableView reloadData];
            [self createHeaderUI];
        });
    
     
    }failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"error = %@",[error localizedDescription]);
        [SVProgressHUD showErrorWithStatus:[error localizedDescription]];
        
    }];
}

#pragma mark - UITableViewDatasource UITableViewDelegate



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
//    if (section ==0) {
//        return 1;
//    }
//    else
        return self.dataArray.count;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//    if (indexPath.row == 0) {
//        LongReviewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"LongReviewCell"];
//
//        tableView.rowHeight = 290;
//        cell.model = _longReviewModel;
//        cell.string = @"查看电影详情";
//        cell.isDetail = YES;
//        return cell;
//    }else{
        NSDictionary * dic = _dataArray[indexPath.row];
    if ([dic[@"type"] isEqualToString:@"text"]) {
        LongContentCell * cell = [tableView dequeueReusableCellWithIdentifier:@"LongContentCell"];
        
        cell.contentText = dic[@"content"];
        return cell;
    }
    else{
        LongImageViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"LongImageViewCell"];
        cell.picUrlString = dic[@"content"];
        return cell;
    }
    
    //}

    
}


@end
